-- golua

local km = require("km")
local json = require("json")
local ioutil = require("ioutil")


-- local err = km.gzip("tests/diff.json","tests/diff.json.gz")
-- if err then error(err) end

-- local err = km.gunzip("tests/diff.json.gz","tests/diff.json.ungz")
-- if err then error(err) end

-- end


local res = km.walk("public/")

local obj = {}
local k = 1

for i,v in ipairs(res) do
    if not v.isDir then
        local newVal = {
            path = v.path,
            size = v.size,
            -- name = v.name,
            -- isDir = v.isDir,
            md5 = km.md5(v.path),
        }
        obj[k] = newVal
        k = k + 1
    end
end


local err = ioutil.write_file("kkbt/diff.json", json.encode(obj))
if err then error(err) end


local result, err = ioutil.read_file("kkbt/diff.old.json")
if err then error(err) end

local oldObj, err= json.decode(result)
if err then error(err) end

local function toMap(files)
    local map = {}
    for _, file in ipairs(files) do
        local key = file.size .. ':' .. file.md5
        map[key] = file
    end
    return map
end

local oldMap = toMap(oldObj)
local newMap = toMap(obj)

-- 比较映射并收集匹配项
local matches = {}
for key, oldFile in pairs(oldMap) do
    if newMap[key] then
        table.insert(matches, oldFile)
    end
end

-- 输出匹配项
local command = ""
for _, match in ipairs(matches) do
    print("Match found:", match.path)
    command = command .. 'rm -rf ./' .. match.path .. '\n'
end

print(command)
os.execute('sh -c "' .. command .. '"')

os.execute('cp kkbt/diff.json kkbt/diff.old.json')

